package com.awesome.spring.service.impl;

import com.awesome.spring.bean.Order;
import com.awesome.spring.bean.TransactionMessage;
import com.awesome.spring.mapper.OrderMapper;
import com.awesome.spring.mapper.TransactionMessageMapper;
import com.awesome.spring.service.OrderService;
import com.awesome.spring.service.TransactionMessageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @program: awesome-spring
 * @description: 事务信息
 * @author: Alex Wu
 * @createDate: 2025-02-13 14:27
 **/
@Slf4j
@Service
public class TransactionMessageServiceImpl extends ServiceImpl<TransactionMessageMapper, TransactionMessage> implements TransactionMessageService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Transactional(rollbackFor = Exception.class)
    public void saveTransactionMessage(String topic, String messageBody) {
        TransactionMessage message = new TransactionMessage();
        message.setTopic(topic);
        message.setMessageBody(messageBody);
        message.setStatus(0); // 0: 待发送
        this.save(message);
    }

    public void changeStatus(Long id, Integer status) {
        TransactionMessage message = new TransactionMessage();
        message.setId(id);
        message.setStatus(status);
        this.updateById(message);
    }

    @Scheduled(fixedRate = 5000) // 每5秒执行一次
    public void retrySendMessage() {
        log.info("开始执行消息发送任务");
        // 查询所有状态为0（待发送）的消息
        List<TransactionMessage> unsentMessages = this.list(new QueryWrapper<TransactionMessage>().eq("status", 0));

        // 遍历每一条未发送的消息
        for (TransactionMessage msg : unsentMessages) {
            try {
                // 发送消息到 RocketMQ
                rocketMQTemplate.convertAndSend(msg.getTopic(), msg.getMessageBody());

                // 更新消息状态为已发送
                msg.setStatus(1);  // 设置为已发送状态
                this.updateById(msg);  // 使用 MyBatis-Plus 提供的 updateById 方法

                log.info("消息成功发送并更新状态: {}", msg);
            } catch (Exception e) {
                // 记录失败日志，稍后重试，重试到一定次数后人工查看
                log.error("消息发送失败，稍后重试: {}", msg, e);
            }
        }
    }



}
